//
//  HistoryController.swift
//  eBooks
//
//  Created by JunMing on 2019/12/11.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit
import FolioReaderKit
class HistoryController: EbookBaseController {
    private var dataSource:Array<Model>?
    private lazy var tableView:UITableView = {
        let tableView = UITableView(frame: self.view.bounds, style: UITableView.Style.plain)
        tableView.register(HistoryCell.self, forCellReuseIdentifier: "download")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.separatorColor = UIColor.RGBA(230, 230, 230, 0.8)
        return tableView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "清空", style: UIBarButtonItem.Style.done, target: self, action: #selector(clearAllDownload))
        view.addSubview(tableView)
        DispatchQueue.global().async {
            self.dataSource = SQLHelper.share.fetchLocalDB(queryType: .queryAll)
            DispatchQueue.main.async { self.tableView.reloadData() }
        }
        
        // 下载鉴权
        registerEvent(eventName: kEbooksBuyVipEventName, block: {[weak self] _ in
            // self?.buyAction(self?.view)
            self?.createRewardAD()
        }, next: false)
    }
    
    @objc func clearAllDownload() {
        showAlert("确定清空", "浏览记录删除后无法恢复，是否删除？", true) { _ in
            SQLHelper.share.deleteAllLocalDB()
        }
    }
}

extension HistoryController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "download") as? HistoryCell
        if cell == nil {
            cell = HistoryCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "download")
        }
        cell!.model = dataSource?[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let count = dataSource?.count {
            return count
        }else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let model = dataSource?[indexPath.row] {
            if !model.isdel {
                openEpubBooks(model)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64.0
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            dataSource?.remove(at: indexPath.row)
            if let model = dataSource?[indexPath.row] {
                SQLHelper.share.deleteLocalDB(model)
                tableView.reloadData()
            }
        }
    }
}

class HistoryCell: UITableViewCell,EbookDownloadProtocol {
    var downloadFails:((_ model:Model) -> Void)?
    fileprivate var cover = ImageLayerView()
    fileprivate var bookName = UILabel()
    fileprivate var bookSize = UILabel()
    fileprivate var deleted = UILabel()
    fileprivate var startDown = UIButton(type: UIButton.ButtonType.system)
    lazy var progressView: JMProgressCircleView = {
        return JMProgressCircleView()
    }()
    
    var model:Model? {
        willSet(newValue) {
            bookName.text = newValue!.title()
            bookSize.text = newValue!.sizeStr()
            cover.loadImage(url: newValue!.coverurl())
            // 已下载且未删除，隐藏下载按钮
            if newValue!.isdel {
                let ima = UIImage(named: "startDownload")
                startDown.setImage(ima, for: UIControl.State.normal)
                startDown.isHidden = false
                deleted.text = "未下载"
            }else {
                print(newValue!.title() ?? "")
                startDown.isHidden = true
                deleted.text = ""
            }
        }
    }
    
    @objc func startDownload(_ sender:UIButton) {
        let showView = fristShowView()
        if model!.isdel && downloadRight(superView: showView!) {
            downloadRun(model: model!) {[weak self] status in
                if status {
                    self?.bookSize.text = self?.model?.sizeStr()
                    self?.deleted.text = ""
                    sender.isHidden = true
                    //sender.setImage(UIImage(named: "downloadDone"), for: UIControl.State.normal)
                }else {
                    self?.downloadFails?((self?.model!)!)
                }
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = UIColor.white
        contentView.addSubview(cover)
        bookName.configLabel(font: UIFont.medium(15), tColor: UIColor.black)
        contentView.addSubview(bookName)
        
        bookSize.configLabel(font: UIFont.regular(13))
        contentView.addSubview(bookSize)
        
        deleted.configLabel(font: UIFont.regular(13),tColor: UIColor.red)
        contentView.addSubview(deleted)
        
        contentView.addSubview(progressView)
        startDown.tintColor = UIColor.RGB(41, 41, 41)
        startDown.addTarget(self, action: #selector(startDownload(_:)), for: UIControl.Event.touchUpInside)
        contentView.addSubview(startDown)
        layout()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func layout() {
        cover.snp.makeConstraints { (make) in
            make.left.equalTo(contentView).offset(10)
            make.width.equalTo(44)
            make.top.equalTo(contentView).offset(5)
            make.bottom.equalTo(contentView).offset(-5)
        }
        
        bookName.snp.makeConstraints { (make) in
            make.left.equalTo(cover.snp_right).offset(10)
            make.top.equalTo(cover.snp_top).offset(5)
            make.right.equalTo(contentView.snp_right).offset(-60)
            make.height.equalTo(20)
        }
        
        bookSize.snp.makeConstraints { (make) in
            make.left.equalTo(cover.snp_right).offset(10)
            make.bottom.equalTo(cover.snp_bottom).offset(-5)
            make.height.equalTo(20)
        }
        
        deleted.snp.makeConstraints { (make) in
            make.left.equalTo(bookSize.snp_right).offset(10)
            make.bottom.equalTo(cover.snp_bottom).offset(-5)
            make.height.equalTo(20)
        }
        
        progressView.snp.makeConstraints { (make) in
            make.right.equalTo(contentView).offset(-10)
            make.centerY.equalTo(contentView.snp_centerY)
            make.height.width.equalTo(40)
        }
        
        startDown.snp.makeConstraints { (make) in
            make.right.equalTo(contentView).offset(-10)
            make.centerY.equalTo(contentView.snp_centerY)
            make.height.width.equalTo(40)
        }
    }
}
